// Copyright (C) 2005 Taylor L. Riché <riche@cs.utexas.edu>
//  
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software 
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// 	$Id: ProcUnit.cc 413 2006-05-26 16:28:49Z richetl $	
//

#include "ProcUnit.hh"

using namespace lee;

ProcUnit::ProcUnit(Scheduler * s, pthread_key_t evK, pthread_key_t exK) : scheduler(s), 
									  eventKey(evK), 
									  exitKey(exK)
{
  MethodWrapper<ProcUnit> * mw = new MethodWrapper<ProcUnit>;
  mw->object = this;
  mw->method = &ProcUnit::process;
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  if(pthread_create(&coreThread, &attr, plainFunction, (void *)mw)) {
    std::cerr << "pthread_create failed" << std::endl;
    std::exit(1);
  }
  pconQueue.setThreshold(100);
}

void
ProcUnit::executePCon(PCon * pcon, bool force) 
{
  assert(pcon->getPacket() != NULL);
  // is nextProc overloaded? 
  // if nextProc is overloaded, call scheduler->assignNewProc(newPCon->getFunction())
  // call getProc again, and proceed
  if(force) {
    pconQueue.forcePush(pcon);
  }
  else if(!pconQueue.push(pcon)) {
    scheduler->assignNewProc(pcon->getFunction());
    pcon->getFunction()->getProc()->executePCon(pcon, FORCE);
  }
}

void
ProcUnit::kill()
{
  pthread_cancel(coreThread);
  return;
}

void
ProcUnit::process()
{
  Synchronized::Scope mutex(this);
  //Logger log;
  pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
//   while(ag == NULL) {
//     wait();
//   }
  while(true) {
    PCon * currPCon = pconQueue.pop();
    Function * currFunction;
    PktData * currData;
    uint32_t currSize;
    {
      Synchronized::Scope mutex(currPCon);
      currFunction = currPCon->getFunction();
      currData = currPCon->getPacket();
      currSize = currPCon->getSize();
    }
    assert(currData != NULL);
    std::list<FuncExit *> * exitList = new std::list<FuncExit *>;
    std::list<Event *> * eventList = new std::list<Event *>;
    pthread_setspecific(exitKey, exitList);
    pthread_setspecific(eventKey, eventList);
    assert(exitList != NULL);
    //    std::pair<std::list<FuncExit *> *, std::list<Event *> *> p = 
    currFunction->processData(currData, currSize);
    for(std::list<FuncExit *>::iterator i = exitList->begin();
	i != exitList->end(); i++) {
      if((*i)->pkt != NULL) {
	// add lookup of internal function in case of a module right
	// here also, when exiting a module, this will be where the
	// pcon is mapped back to the, "outside world". Need a way for
	// the application graph to be dependent upon which function
	// was the last function executed. therefore, make ag stick to
	// the functions not the procunits.

	Composable * nextComp = currFunction->getCont()->getNextComposable(currFunction->getName(),(*i)->exit);
	Function * nextFunc;
	nextFunc = dynamic_cast<Function *>(nextComp);
	PCon * newPCon = new PCon();
	if(nextFunc != NULL) {
	  // the next composable is just a function
	  newPCon->setFunction(nextFunc);
	}
	else {
	  // the next composable is a module
	  while(nextFunc == NULL) {
	    Module * mod = dynamic_cast<Module *>(nextComp);
	    assert(mod != NULL);
	    if(mod->isExit(currFunction->getName(), (*i)->exit)) {
	      // this is an exit point of the module
	      nextComp = mod->getCont()->getNextComposable(mod->getName(), 
							   mod->mapExit(currFunction->getName(), 
									(*i)->exit));
	      nextFunc = dynamic_cast<Function *>(nextComp);
	    }
	    else {
	      // this is an entry into a module
	      nextComp = mod->getStart();
	      nextFunc = dynamic_cast<Function *>(nextComp);
	    }
	  }
	  newPCon->setFunction(nextFunc);
	}
	{
	  Synchronized::Scope mutex(newPCon);
	  newPCon->setPacket((*i)->pkt);
	  newPCon->setSize((*i)->pktSize);
	}
	// TODO (0.5.0) : Change here for load balancing
	ProcUnit * nextProc = newPCon->getFunction()->getProc();
	assert(newPCon->getPacket() != NULL);
	nextProc->executePCon(newPCon);
      }
      delete *i;
    }
    if(currFunction->isRecursive()) {
      PCon * newPCon = new PCon();
      newPCon->setFunction(currFunction);
      newPCon->setPacket(NULL);
      // TODO (0.5.0) : Change here for load balancing... maybe.
      ProcUnit * nextProc = newPCon->getFunction()->getProc();
      nextProc->executePCon(newPCon);
    }
    assert(eventList->empty());
    for(std::list<Event *>::iterator i = eventList->begin();
	i != eventList->end(); i++) {
      EventWrapper * newWrapper = new EventWrapper;
      newWrapper->master = currFunction->getMasterSub();
      newWrapper->ev = *i;
      scheduler->getCU()->deliver(newWrapper);
      //log.write("event");
    }
    delete exitList;
    delete eventList;
    delete currPCon;
  }
};

